﻿using IENMService.DAO;
using IENMService.Model;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Sugar.hisEnties;
using Sugar.lisEnties;
using Sugar.portalEnties;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Xml.Linq;
using static Dm.net.buffer.ByteArrayBuffer;

namespace IENMService.Service
{
    /// <summary>
    /// 护理管理接口服务
    /// </summary>
    public class IENMInterfaceService : IENMInterface
    {
        #region 初始化
        /// <summary>
        /// 日志对象
        /// </summary>
        private readonly ILogger<IENMInterfaceService> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        public IENMInterfaceService(ILogger<IENMInterfaceService> logger)
        {
            _logger = logger;
        }
        #endregion

        /// <summary>
        /// 4.1.1.1 获取科室列表
        /// </summary>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<Dept>> IENMInterface.getDepts(DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<Dept>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间 
            var xtsj = his.GetDate();

            var ksdmlist = await his.Queryable<GY_KSDM>().Where(s => s.JGID == 1).ToPageListAsync(pageNum, pageSize);

            foreach (var ksdm in ksdmlist)
            {
                var dept = new Dept
                {
                    deptCode = ksdm.KSDM.ToString(),
                    deptName = ksdm.KSMC.ToString(),
                    parentDeptCode = ksdm.SJKS.ToString(),
                    sort = decimal.Parse(ksdm.PLSX),
                    deptFlag = ksdm.BQSY == "Y" ? "1" :"2",
                    updateTime = xtsj,
                };
                result.Add(dept);
            }

            return result;

        }

        /// <summary>
        /// 4.1.1.2 获取科室类型
        /// </summary>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<DeptType>> IENMInterface.getDeptTypes(DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<DeptType>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ksdmlist = await his.Queryable<GY_KSDM>().Where(s => s.JGID == 1).ToPageListAsync(pageNum, pageSize);

            foreach (var ksdm in ksdmlist)
            {
                //科室类型 1:门诊科室 2:住院科室 3:挂号科室4:药房科室 5:麻醉科室 6:手术室 7:执行科室8:开单科室 9: 药库科室
                var deptTypeCode = "";
                var deptTypeName = "";

                if (ksdm.MZSY == "Y")
                {
                    deptTypeCode = "1";
                    deptTypeName = "门诊科室";
                }
                else if (ksdm.ZYSY == "Y" || ksdm.BQSY == "Y")
                {
                    deptTypeCode = "2";
                    deptTypeName = "住院科室";
                }
                else if(ksdm.YJSY == "Y")
                {
                    deptTypeCode = "7";
                    deptTypeName = "执行科室";
                }
                else
                {
                    deptTypeCode = "2";
                    deptTypeName = "住院科室";
                }

                if (ksdm.KSMC.Contains("麻醉"))
                {
                    deptTypeCode = "5";
                    deptTypeName = "麻醉科室";
                }
                if (ksdm.KSMC.Contains("手术室"))
                {
                    deptTypeCode = "6";
                    deptTypeName = "手术室";
                }

                var deptType = new DeptType
                {
                    deptCode = ksdm.KSDM.ToString("0"),
                    deptName = ksdm.KSMC.ToString(),
                    deptTypeCode = deptTypeCode,
                    deptTypeName = deptTypeName,
                    updateTime = xtsj,
                };
                result.Add(deptType);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.3 获取科室与病区关联关系
        /// </summary>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<DeptWardRelation>> IENMInterface.getDeptWardRelation(DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<DeptWardRelation>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ksdmlist = await his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.ZYSY == "Y" && s.BQSY == "Y").ToPageListAsync(pageNum, pageSize);

            foreach (var ksdm in ksdmlist)
            {
                var deptWardRelation = new DeptWardRelation
                {
                    deptCode = ksdm.KSDM.ToString("0"),
                    deptName = ksdm.KSMC.ToString(),
                    wardCode = ksdm.KSDM.ToString("0"),
                    wardName = ksdm.KSMC.ToString(),
                    deleteFlag = "0",
                    updateTime = xtsj,
                };
                result.Add(deptWardRelation);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.4 获取职工与科室关系
        /// </summary>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<UsersDept>> IENMInterface.getUsersDept(DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<UsersDept>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ygdmlist = await his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.ZFPB == 0).ToPageListAsync(pageNum, pageSize);

            foreach (var ygdm in ygdmlist)
            {
                var usersDept = new UsersDept
                {
                    userId = ygdm.YGDM?.ToString(),
                    userName = ygdm?.YGXM?.ToString(),
                    userCode = ygdm.YGBH?.ToString(),
                    loginName = ygdm.YGBH?.ToString(),
                    loginPass = ygdm.YGMM?.ToString(),
                    deptCode = ygdm.KSDM != null ? ygdm.KSDM.ToString("0") : "",
                    deptName = ygdm.KSDM != null ? his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == ygdm.KSDM).First()?.KSMC : "",
                    updateTime = xtsj,
                };
                result.Add(usersDept);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.5 获取职工信息
        /// </summary>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<User>> IENMInterface.getUsers(DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<User>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ygdmlist = await his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.ZFPB == 0).ToPageListAsync(pageNum, pageSize);

            foreach (var ygdm in ygdmlist)
            {
                var user = new User
                {
                    userId = ygdm.YGDM?.ToString(),
                    userName = ygdm.YGXM?.ToString(),
                    userGender = ygdm.YGXB?.ToString("0"),
                    idCard = ygdm.SFZH?.ToString(),
                    userCode = ygdm.YGBH?.ToString(),
                    loginName = ygdm.YGBH?.ToString(),
                    loginPass = ygdm.YGMM?.ToString(),
                    passwordEncryptType = "MD5",
                    caUniqueId = "",
                    updateTime = xtsj,
                };
                result.Add(user);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.6 获取职工与角色关系信息
        /// </summary>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<UserRoles>> IENMInterface.getUserRoles(DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<UserRoles>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ygdmlist = await his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.ZFPB == 0).ToPageListAsync(pageNum, pageSize);

            foreach (var ygdm in ygdmlist)
            {
                //职工角色 1:护士 2:医师 3:护理部人员 4:护理部主任 5:护理副院长 6:信息科人员 7:系统管理员 8：病区护士长
                var roleCode = "";
                var roleName = "";

                if (ygdm.YGJB == 1 || ygdm.YGJB == 2 || ygdm.YGJB == 3 || ygdm.YGJB == 4 ||
                    ygdm.YGJB == 10 || ygdm.YGJB == 11 || ygdm.YGJB == 12 || ygdm.YGJB == 13)
                {
                    roleCode = "2";
                    roleName = "医师";
                }
                else if (ygdm.YGJB == 5 || ygdm.YGJB == 6 || ygdm.YGJB == 7 || ygdm.YGJB == 8 || ygdm.YGJB == 9) //护师
                {
                    roleCode = "1";
                    roleName = "护士";
                }
                else
                {
                    roleCode = "1";
                    roleName = "护士";
                }

                if (ygdm.YGZW == 5 || ygdm.YGZW == 7)
                {
                    roleCode = "8";
                    roleName = "病区护士长";
                }

                var userRoles = new UserRoles
                {
                    userId = ygdm.YGDM.ToString(),
                    userName = ygdm.YGXM.ToString(),
                    userCode = ygdm.YGBH.ToString(),
                    roleCode = roleCode,
                    roleName = roleName,
                    updateTime = xtsj,
                };
                result.Add(userRoles);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.7 获取床位列表信息
        /// </summary>
        /// <param name="deptCode">科室编号</param>
        /// <param name="updateTime">数据更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns></returns>
        async Task<List<DeptBeds>> IENMInterface.getDeptBeds(string deptCode, DateTime updateTime, int pageNum, int pageSize)
        {
            var result = new List<DeptBeds>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ksdm = decimal.Parse(deptCode);

            var cwszlist = await his.Queryable<ZY_CWSZ>().Where(a => a.JGID == 1 && a.CWKS == ksdm).ToPageListAsync(pageNum, pageSize);

            foreach (var cwsz in cwszlist)
            {
                var zdycwf = 0.00M;
                var zdycw = his.Queryable<ZY_ZDYCW, GY_YLMX>((a, b) => a.FYXH == b.FYXH)
                    .Where((a, b) => a.JGID == 1 && b.JGID == 1 && b.ZFPB == 0 && a.BRCH == cwsz.BRCH).First();

                if (zdycw == null)
                {
                    zdycwf = 0;
                }
                else
                {
                    zdycwf = zdycw.FYDJ;
                }

                var deptBeds = new DeptBeds
                {
                    bedNo = cwsz.BRCH,
                    bedName = cwsz.BRCH,
                    deptCode = cwsz.CWKS.ToString("0"),
                    wardCode = cwsz.KSDM.ToString("0"),
                    bedClass = "",
                    bedCost = cwsz.ZDYCW == 1 ? zdycwf : cwsz.CWFY,
                    bedStatus = cwsz.ZYH == null ? "0" : "1", //床位状态，床位的占用状态 0:空闲 1:占用
                    roomNo = cwsz.FJHM,
                    updateTime = xtsj,
                };
                result.Add(deptBeds);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.8 获取患者信息
        /// </summary>
        /// <param name="patientId">患者唯一号</param>
        /// <param name="inpNo">住院号</param>
        /// <param name="visitId">入院次数</param>
        /// <param name="inHospital">0：获取全部，1：只获取在院</param>
        /// <param name="deptCode">科室编号</param>
        /// <param name="admissiontime">入院时间</param>
        /// <param name="updateTime">更新时间</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页条数</param>
        /// <returns></returns>
        async Task<List<Patient>> IENMInterface.getPatients(string? patientId, string? inpNo, int? visitId, string? inHospital, string? deptCode, DateTime? admissiontime, DateTime? updateTime, int pageNum, int pageSize)
        {
            var result = new List<Patient>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            //var xtsj = his.GetDate();

            //var zyh = decimal.Parse(patientId);

            var cypb = new decimal?[5];

            if (!string.IsNullOrWhiteSpace(inHospital))
            {
                if (inHospital == "0") //0：获取全部，1：只获取在院
                {
                    cypb[0] = 0;
                    cypb[1] = 1;
                    cypb[2] = 2;
                    cypb[3] = 8;
                    cypb[4] = 99;
                }
                else
                {
                    cypb[0] = 0;
                }
            }

            var Patlist = await his.Queryable<V_HJJ_IENM_Patients>()
                .WhereIF(!string.IsNullOrWhiteSpace(patientId), (a) => a.patientId == patientId )
                .WhereIF(!string.IsNullOrWhiteSpace(inpNo), (a) => a.inpNo == inpNo)
                .WhereIF(!string.IsNullOrWhiteSpace(inHospital), (a) => cypb.Contains(a.CYPB))
                .WhereIF(!string.IsNullOrWhiteSpace(deptCode), (a) => a.deptCode == deptCode)
                .WhereIF(!string.IsNullOrWhiteSpace(admissiontime.ToString()), (a) => a.admissionTime >= admissiontime)
                .WhereIF(!string.IsNullOrWhiteSpace(updateTime.ToString()), (a) => a.XGSJ >= updateTime)
                .ToPageListAsync(pageNum, pageSize);

            foreach (var Pat in Patlist)
            {
                var patient = new Patient
                {
                    patientId = Pat.patientId, 
                    medicalVisitNo = Pat.medicalVisitNo, 
                    inpNo = Pat.inpNo, 
                    visitId = Pat.visitId, 
                    roomNo = Pat.roomNo, 
                    bedNo = Pat.bedNo, 
                    admissionDeptCode = Pat.admissionDeptCode, 
                    admissionDeptName = Pat.admissionDeptName, 
                    admissionWardCode = Pat.admissionWardCode, 
                    admissionWardName = Pat.admissionWardName, 
                    deptCode = Pat.deptCode, 
                    deptName = Pat.deptName, 
                    wardCode = Pat.wardCode, 
                    wardName = Pat.wardName, 
                    patientName = Pat.patientName, 
                    gender = Pat.gender, 
                    chargeType = Pat.chargeType, 
                    age = Pat.age ?? 0, 
                    ageMonth = Pat.ageMonth, 
                    ageDay = Pat.ageDay, 
                    ageHour = Pat.ageHour, 
                    ageMinute = Pat.ageMinute, 
                    birthDate = (DateTime?)Pat.birthDate, 
                    idCard = Pat.idCard, 
                    nationality = Pat.nationality, 
                    nation = Pat.nation, 
                    maritalStatus = Pat.maritalStatus?.ToString("0"), 
                    education = Pat.education, 
                    accountAddress = Pat.accountAddress, 
                    onsetSolarTerm = Pat.onsetSolarTerm, 
                    syndromeType = Pat.syndromeType, 
                    admissionForm = Pat.admissionForm, 
                    contactName = Pat.contactName, 
                    relationShip = Pat.relationShip, 
                    phone = Pat.phone, 
                    contactPhone = Pat.contactPhone, 
                    admissionTime = Pat.admissionTime, 
                    deptedTime = Pat.deptedTime, 
                    leaveTime = (DateTime?)Pat.leaveTime, 
                    actualLeaveTime = (DateTime?)Pat.actualLeaveTime, 
                    diagnosisCode = Pat.diagnosisCode, 
                    diagnosisName = Pat.diagnosisName, 
                    doctorCode = Pat.doctorCode, 
                    doctorName = Pat.doctorName, 
                    nurseCode = Pat.nurseCode, 
                    nurseName = Pat.nurseName, 
                    nurseLevel = Pat.nurseLevel, 
                    nurseLevelName = Pat.nurseLevelName, 
                    headNurseCode = Pat.headNurseCode, 
                    headNurseName = Pat.headNurseName, 
                    headDeptCode = Pat.headDeptCode, 
                    headDeptName = Pat.headDeptName,
                    CYPB = Pat.CYPB,
                };
                result.Add(patient);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.9 获取患者转科记录信息
        /// </summary>
        /// <param name="PATIENT_ID">患者唯一编号</param>
        /// <param name="INP_NO">住院号</param>
        /// <param name="VISIT_ID">住院次数</param>
        /// <param name="START_TIME">转入或转出开始时间</param>
        /// <param name="END_TIME">转入或转出结束时间</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<TransferRecord>> IENMInterface.getTransferRecord(string? PATIENT_ID, string? INP_NO, string? VISIT_ID, DateTime? START_TIME, DateTime? END_TIME, DateTime? UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<TransferRecord>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            //var xtsj = his.GetDate();

            var zkjllist = await his.Queryable<ZY_ZKJL,ZY_BRRY>((a,b) => a.ZYH == b.ZYH)
                .Where((a, b) => a.HCLX == 3)
                .WhereIF(!string.IsNullOrWhiteSpace(PATIENT_ID), (a) => a.ZYH == decimal.Parse(PATIENT_ID))
                .WhereIF(!string.IsNullOrWhiteSpace(INP_NO), (a, b) => b.ZYHM == INP_NO)
                .WhereIF(!string.IsNullOrWhiteSpace(START_TIME.ToString()), (a) => a.YSSQRQ >= START_TIME)
                .WhereIF(!string.IsNullOrWhiteSpace(END_TIME.ToString()), (a) => a.YSSQRQ <= END_TIME)
                .WhereIF(!string.IsNullOrWhiteSpace(UPDATE_TIME.ToString()), (a) => a.YSSQRQ >= UPDATE_TIME)
                .Select((a, b) => new {
                    a.JLXH,
                    a.ZYH,
                    a.HCLX,
                    a.YSSQRQ,
                    a.YSSQGH,
                    a.BQSQRQ,
                    a.BQSQGH,
                    a.BQZXRQ,
                    a.BQZXGH,
                    a.YSZXRQ,
                    a.YSZXGH,
                    a.ZXBZ,
                    a.HQCH,
                    a.HHCH,
                    a.HQBQ,
                    a.HHBQ,
                    a.HQKS,
                    a.HHKS,
                    a.HQYS,
                    a.HHYS,
                    a.JGID,
                    a.TWDZKSJ
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var zkjl in zkjllist)
            {
                var transferRecord = new TransferRecord
                {
                    PATIENT_ID = zkjl.ZYH.ToString("0"),
                    INP_NO = his.Queryable<ZY_BRRY>().Where(s => s.JGID == 1 && s.ZYH == zkjl.ZYH).First().ZYHM,
                    VISIT_ID = 1,
                    TRANSFER_OUT_DEPT_CODE = zkjl.HQKS?.ToString("0"),
                    TRANSFER_OUT_DEPT_NAME = !string.IsNullOrWhiteSpace(zkjl.HQKS?.ToString()) ? his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == zkjl.HQKS).First().KSMC : null,
                    TRANSFER_OUT_WARD_CODE = zkjl.HQBQ?.ToString("0"),
                    TRANSFER_OUT_WARD_NAME = !string.IsNullOrWhiteSpace(zkjl.HQBQ?.ToString()) ? his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == zkjl.HQBQ).First().KSMC : null,
                    TRANSFER_OUT_USER_CODE = zkjl.BQSQGH?.ToString(),
                    TRANSFER_OUT_USER_NAME = !string.IsNullOrWhiteSpace(zkjl.BQSQGH?.ToString()) ? his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == zkjl.BQSQGH).First().YGXM : null,
                    TRANSFER_OUT_BED_NO = zkjl.HQCH?.ToString(),
                    TRANSFER_OUT_DATE = (DateTime?)zkjl.BQSQRQ,
                    TRANSFER_IN_DEPT_CODE = zkjl.HHKS?.ToString("0"),
                    TRANSFER_IN_DEPT_NAME = !string.IsNullOrWhiteSpace(zkjl.HHKS?.ToString()) ? his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == zkjl.HHKS).First().KSMC : null,
                    TRANSFER_IN_WARD_CODE = zkjl.HHBQ?.ToString("0"),
                    TRANSFER_IN_WARD_NAME = !string.IsNullOrWhiteSpace(zkjl.HHBQ?.ToString()) ? his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == zkjl.HHBQ).First().KSMC : null,
                    TRANSFER_IN_USER_CODE = zkjl.BQZXGH?.ToString(),
                    TRANSFER_IN_USER_NAME = !string.IsNullOrWhiteSpace(zkjl.BQZXGH?.ToString()) ? his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == zkjl.BQZXGH).First().YGXM : null,
                    TRANSFER_IN_BED_NO = zkjl.HHCH?.ToString(),
                    TRANSFER_IN_DATA = (DateTime?)zkjl.BQZXRQ
                };
                result.Add(transferRecord);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.10 获取患者出院撤回记录
        /// </summary>
        /// <param name="DEPT_CODE">科室编号</param>
        /// <param name="START_TIME">开始时间</param>
        /// <param name="END_TIME">结束时间</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页条数</param>
        /// <returns></returns>
        async Task<List<PatientLeaveRevoke>> IENMInterface.getPatientLeaveRevoke(string? DEPT_CODE, DateTime? START_TIME, DateTime? END_TIME, DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<PatientLeaveRevoke>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            //var xtsj = his.GetDate();

            //var ksdm = decimal.Parse(DEPT_CODE);

            var zkjllist = await his.Queryable<ZY_CYJL,ZY_BRRY>((a, b) => a.ZYH == b.ZYH)
                .Where((a, b) => a.JGID == 1 && a.CYFS == 0 && a.CZLX == 4)
                .WhereIF(!string.IsNullOrWhiteSpace(DEPT_CODE), (a, b) => b.BRKS == decimal.Parse(DEPT_CODE))
                .WhereIF(!string.IsNullOrWhiteSpace(START_TIME.ToString()), (a) => a.CZRQ >= START_TIME)
                .WhereIF(!string.IsNullOrWhiteSpace(END_TIME.ToString()), (a) => a.CZRQ <= END_TIME)

                .Select((a, b) => new { 
                    a.ZYH,
                    b.ZYHM,
                    b.BRKS,
                    a.CZR,
                    a.CZRQ
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var zkjl in zkjllist)
            {
                var patientLeaveRevoke = new PatientLeaveRevoke
                {
                    PATIENT_ID = zkjl.ZYH.ToString("0"),
                    INP_NO = zkjl.ZYHM,
                    VISIT_ID = 1,
                    DEPT_CODE = zkjl.BRKS.ToString("0"),
                    DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == zkjl.BRKS).First().KSMC,
                    OPERATE_USER_CODE = zkjl.CZR.ToString(),
                    OPERATE_USER_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == zkjl.CZR).First().YGXM,
                    OPERATE_TIME = (DateTime?)zkjl.CZRQ

                };
                result.Add(patientLeaveRevoke);
            }

            return result;

        }

        /// <summary>
        /// 4.1.1.11 获取医嘱用法信息
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页条数</param>
        /// <returns></returns>
        async Task<List<DoctorAdviceUsage>> IENMInterface.getDoctorAdviceUsage(DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<DoctorAdviceUsage>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ypyflist = await his.Queryable<ZY_YPYF>().Where(a => a.ZFBZ == 0).ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var ypyf in ypyflist)
            {
                var doctorAdviceUsage = new DoctorAdviceUsage
                {
                    CODE = ypyf.YPYF.ToString("0"),
                    NAME = ypyf.XMMC,
                    GB_CODE = "",
                    GB_NAME = "",
                    LATIN_ABBREVIATION = ypyf.PYDM,
                    PINYIN_CODE = ypyf.PYDM,
                    MODEL_TAKE_DRUG = "",
                    MODEL_TAKE_DRUG_NAME = "",
                    UPDATE_TIME = xtsj
                };
                result.Add(doctorAdviceUsage);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.12 获取医嘱类型信息
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <returns></returns>
        async Task<List<DoctorAdviceType>> IENMInterface.getDoctorAdviceType(DateTime UPDATE_TIME)
        {
            var result = new List<DoctorAdviceType>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var yysxArr = new string[] { "1","2","3","4"};

            foreach (var yysx in yysxArr)
            {
                var doctorAdviceType = new DoctorAdviceType
                {
                    CODE = yysx,
                    NAME = yysx switch { "1" => "长期", "2" => "临时", "3" => "急诊", "4" => "出院带药", _ => "临时" },
                    GB_CODE = "",
                    GB_NAME = "",
                    UPDATE_TIME = xtsj

                };

                result.Add(doctorAdviceType);
            }

            return result;

        }

        /// <summary>
        /// 4.1.1.13 获取医嘱类别信息
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <returns></returns>
        async Task<List<DoctorAdviceCategory>> IENMInterface.getDoctorAdviceCategory(DateTime UPDATE_TIME)
        {
            var result = new List<DoctorAdviceCategory>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ydyzlblist = await his.Queryable<EMR_YDYZLB>().Where(a => a.ZXBZ == 0).ToListAsync();

            foreach (var ydyzlb in ydyzlblist)
            {
                var doctorAdviceCategory = new DoctorAdviceCategory
                {
                    CODE = ydyzlb.YDYZLB.ToString("0"),
                    NAME = ydyzlb.LBMC,
                    GB_CODE = "",
                    GB_NAME = "",
                    UPDATE_TIME = xtsj
                };
                result.Add(doctorAdviceCategory);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.14 获取医嘱状态信息
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <returns></returns>
        async Task<List<DoctorAdviceStatus>> IENMInterface.getDoctorAdviceStatus(DateTime UPDATE_TIME)
        {
            var result = new List<DoctorAdviceStatus>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var yzztlist = await his.Queryable<GY_XTPZ>().Where(a => a.DMLB == 302 && a.DMSB != 0).ToListAsync();

            foreach (var yzzt in yzztlist)
            {
                var doctorAdviceStatus = new DoctorAdviceStatus
                {
                    CODE = yzzt.PZBH?.ToString("0"),
                    NAME = yzzt.DMMC,
                    GB_CODE = "",
                    GB_NAME = "",
                    UPDATE_TIME = xtsj
                };
                result.Add(doctorAdviceStatus);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.15 获取医嘱频次信息
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <returns></returns>
        async Task<List<DoctorAdviceFrequency>> IENMInterface.getDoctorAdviceFrequency(DateTime UPDATE_TIME)
        {
            var result = new List<DoctorAdviceFrequency>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var sypclist = await his.Queryable<GY_SYPC>().Where(a => a.JGID == 1 && a.ZXBZ == 0).ToListAsync();

            foreach (var sypc in sypclist)
            {
                var doctorAdviceFrequency = new DoctorAdviceFrequency
                {
                    CODE = sypc.PCBM,
                    NAME = sypc.PCMC,
                    LATIN_ABBREVIATION = sypc.PCBM,
                    PINYIN_CODE = sypc.PCBM,
                    TIMES = sypc.MRCS.ToString("0"),
                    FREQUENCY_OF_TIME = sypc.ZXSJ.ToString(),
                    GB_CODE = "",
                    GB_NAME = "",
                    UPDATE_TIME = xtsj
                };
                result.Add(doctorAdviceFrequency);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.16 获取医嘱详细信息
        /// </summary>
        /// <param name="DOCTOR_ADVICE_ID">医嘱号，支持多个用逗号拼接</param>
        /// <param name="INP_NO">住院号</param>
        /// <param name="VISIT_ID">入院次数</param>
        /// <param name="ORDERING_DEPT_CODE">开单科室编号</param>
        /// <param name="STARTTIME_FROM">医嘱开始时间（检索开始时间）</param>
        /// <param name="STARTTIME_TO">医嘱开始时间（检索结束时间）</param>
        /// <param name="ISENABLE">是否启用，1 是，0 否,默认全部</param>
        /// <param name="ISSTOP">是否停止，1 是，0 否,默认全部</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<DoctorAdvice>> IENMInterface.getDoctorAdvice(string? DOCTOR_ADVICE_ID, string? INP_NO, string? VISIT_ID, string? ORDERING_DEPT_CODE, DateTime? STARTTIME_FROM, DateTime? STARTTIME_TO, int? ISENABLE, int? ISSTOP, DateTime? UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<DoctorAdvice>();

            //连接数据库
            var his = SugarBase.GetIntance();

            var adviceid = new string[] { };

            if (!string.IsNullOrWhiteSpace(DOCTOR_ADVICE_ID))
            {
                adviceid = DOCTOR_ADVICE_ID.Split(",");
            }

            var docadvicelist = await his.Queryable<V_HJJ_IENM_DoctorAdvice>()
                .WhereIF(!string.IsNullOrWhiteSpace(DOCTOR_ADVICE_ID), (a) => adviceid.Contains(a.DOCTOR_ADVICE_ID))
                .WhereIF(!string.IsNullOrWhiteSpace(INP_NO), (a) => a.INP_NO == INP_NO)
                .WhereIF(!string.IsNullOrWhiteSpace(ORDERING_DEPT_CODE), (a) => a.ORDERING_DEPT.ToString() == ORDERING_DEPT_CODE)
                .WhereIF(!string.IsNullOrWhiteSpace(STARTTIME_FROM.ToString()), (a) => a.STARTTIME >= STARTTIME_FROM)
                .WhereIF(!string.IsNullOrWhiteSpace(STARTTIME_TO.ToString()), (a) => a.STARTTIME <= STARTTIME_TO)
                .WhereIF(ISENABLE == 1, (a) => a.STOP_DOCTOR_CODE == null || a.STOP_DOCTOR_CODE == "")
                .WhereIF(ISSTOP == 1, (a) => a.STOP_DOCTOR_CODE != null || a.STOP_DOCTOR_CODE != "")
                .WhereIF(!string.IsNullOrWhiteSpace(UPDATE_TIME.ToString()), (a) => a.XGSJ >= UPDATE_TIME)
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var docadvice in docadvicelist)
            {
                var doctorAdvice = new DoctorAdvice
                {
                    PATIENT_ID = docadvice.PATIENT_ID, 
                    MEDICAL_VISIT_NO = docadvice.MEDICAL_VISIT_NO, 
                    INP_NO = docadvice.INP_NO, 
                    VISIT_ID  = docadvice.VISIT_ID, 
                    DOCTOR_ADVICE_ID = docadvice.DOCTOR_ADVICE_ID, 
                    DOCTOR_ADVICE_SERIAL_NUMBER = docadvice.DOCTOR_ADVICE_SERIAL_NUMBER, 
                    SERIAL_NUMBER = docadvice.SERIAL_NUMBER, 
                    DOCTOR_ADVICE_TYPE_CODE = docadvice.DOCTOR_ADVICE_TYPE_CODE, 
                    DOCTOR_ADVICE_CATEGORY_CODE = docadvice.DOCTOR_ADVICE_CATEGORY_CODE, 
                    DOCTOR_ADVICE_STATUS_CODE = docadvice.DOCTOR_ADVICE_STATUS_CODE, 
                    DOCTOR_ADVICE_FREQUENCY_CODE = docadvice.DOCTOR_ADVICE_FREQUENCY_CODE, 
                    DOCTOR_ADVICE_USAGE_CODE = docadvice.DOCTOR_ADVICE_USAGE_CODE.ToString("0"), 
                    IS_DOUBLE = docadvice.IS_DOUBLE, 
                    CLINICAL_PROJECT_CODE = docadvice.CLINICAL_PROJECT_CODE, 
                    CLINICAL_PROJECT_NAME = docadvice.CLINICAL_PROJECT_NAME, 
                    DRUG_DIC_CODE = docadvice.DRUG_DIC_CODE, 
                    SPECIFICATION = docadvice.SPECIFICATION, 
                    SPECIFICATION_UNIT = docadvice.SPECIFICATION_UNIT, 
                    DOSAGE_UNITS = docadvice.DOSAGE_UNITS, 
                    DOSAGE_UNITS_AMOUNT = docadvice.DOSAGE_UNITS_AMOUNT, 
                    DOSAGE = docadvice.DOSAGE, 
                    TOTAL_DOSAGE = docadvice.TOTAL_DOSAGE, 
                    STARTTIME = docadvice.STARTTIME, 
                    ENABLETIME = (DateTime?)docadvice.ENABLETIME, 
                    ENABLE_NURSE_CODE = docadvice.ENABLE_NURSE_CODE, 
                    ENABLE_NURSE_NAME = docadvice.ENABLE_NURSE_NAME, 
                    STOP_DOCTOR_CODE = docadvice.STOP_DOCTOR_CODE, 
                    STOP_DOCTOR_NAME = docadvice.STOP_DOCTOR_NAME, 
                    STOP_NURSE_CODE = docadvice.STOP_NURSE_CODE, 
                    STOP_NURSE_NAME = docadvice.STOP_NURSE_NAME, 
                    CHARGE_FLAG = docadvice.CHARGE_FLAG, 
                    REMARK = docadvice.REMARK, 
                    STOP_TIME = (DateTime?)docadvice.STOP_TIME, 
                    DOCTOR_CODE = docadvice.DOCTOR_CODE, 
                    DOCTOR_NAME = docadvice.DOCTOR_NAME, 
                    ORDERING_DEPT = docadvice.ORDERING_DEPT.ToString("0"), 
                    ORDERING_DEPT_NAME = docadvice.ORDERING_DEPT_NAME, 
                    HANDLETIME = docadvice.HANDLETIME, 
                    DOCTOR_ADVICE_STATUS_NAME = docadvice.DOCTOR_ADVICE_STATUS_NAME.ToString(), 
                    PRICE = docadvice.PRICE ?? 0, 
                    SELF_DRUG = docadvice.SELF_DRUG, 
                    TAKEAWAY_DRUG = docadvice.TAKEAWAY_DRUG, 
                    GET_DRUG_WAY = docadvice.GET_DRUG_WAY
                };
                result.Add(doctorAdvice);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.17 获取疾病名称信息
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<ICD10>> IENMInterface.getICD10(DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<ICD10>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var jbbmlist = await his.Queryable<GY_JBBM>().Where(a => a.DMLB == 10).ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var jbbm in jbbmlist)
            {
                var iCD10 = new ICD10
                {
                    ICD10_CODE = jbbm.ICD9,
                    ICD10_MC = jbbm.JBMC,
                    ICD10_PINYIN_CODE = jbbm.PYDM,
                    ICD10_REMARK = jbbm.BZXX,
                    UPDATE_TIME = xtsj
                };
                result.Add(iCD10);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.18 获取检验申请信息
        /// </summary>
        /// <param name="APPLY_DEPT_CODE">申请科室编号</param>
        /// <param name="APPLY_DATE_FROM">检验申请开始时间</param>
        /// <param name="APPLY_DATE_TO">检验申请结束时间</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE"></param>
        /// <returns></returns>
        async Task<List<Examine>> IENMInterface.getExamine(string? APPLY_DEPT_CODE, DateTime? APPLY_DATE_FROM, DateTime? APPLY_DATE_TO, DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<Examine>();

            //连接数据库
            var his = SugarBase.GetIntance();
            var lis = SugarBase.GetIntance("lis");
            //获取系统时间
            var xtsj = his.GetDate();

            var jysqdlist = await lis.Queryable<L_LIS_SQD, L_LIS_SQDMX>((a, b) => a.DOCTREQUESTNO == b.DOCTREQUESTNO)
                .Where((a,b) => a.JGID == 1 && a.STAYHOSPITALMODE == 2)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DEPT_CODE), (a) => a.SECTION == APPLY_DEPT_CODE)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DATE_FROM.ToString()), (a, b) => a.REQUESTTIME >= APPLY_DATE_FROM)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DATE_TO.ToString()), (a, b) => a.REQUESTTIME <= APPLY_DATE_TO)

                .Select((a, b) => new { 
                    a.DOCTREQUESTNO,
                    a.REQUESTTIME,
                    a.REQUESTER,
                    a.SQDSTATUS,
                    a.STAYHOSPITALMODE,
                    a.BRXZ,
                    a.PATIENTID,
                    a.PATIENTNAME,
                    a.SEX,
                    a.BIRTHDAY,
                    a.AGE,
                    a.AGE_UNIT,
                    a.SECTION,
                    a.BED_NO,
                    a.REQUESTMODE,
                    a.DIAGNOSTIC,
                    a.EXAMINAIM,
                    a.EXAMINAIMCODE,
                    a.JZXH,
                    a.BRID,
                    a.SFZH,
                    a.LXDH,
                    a.BAHM,
                    b.PREHYID,
                    b.ZTMC,
                    b.YSYZBH

                })
                .Distinct()
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var jysqd in jysqdlist)
            {
                var examine = new Examine
                {
                    PATIENT_ID = jysqd.JZXH?.ToString("0"),
                    INP_NO = jysqd.PATIENTID,
                    VISIT_ID = 1,
                    EXAM_PROJECT_CODE = jysqd.EXAMINAIMCODE,
                    EXAM_PROJECT_NAME = jysqd.EXAMINAIM,
                    APPLY_ID = jysqd.DOCTREQUESTNO,
                    APPLY_SERIAL_NUMBER = "1",
                    DOCTOR_ADVICE_ID = jysqd.YSYZBH?.ToString("0"),
                    APPLY_DEPT_CODE = jysqd.SECTION,
                    APPLY_DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM.ToString() == jysqd.SECTION).First().KSMC,
                    APPLY_DOCTOR_CODE = jysqd.REQUESTER,
                    APPLY_DOCTOR_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == jysqd.REQUESTER).First().YGXM,
                    APPLY_DATE = (DateTime)jysqd.REQUESTTIME,
                    EXAM_CAUSE = jysqd.DIAGNOSTIC,
                    SPECIMEN = "",
                    BARCODE = "",
                    EXAM_DATE = null,
                    EXAM_RESULT_STATUS = "",
                    EXECUTE_DEPT_CODE = "314",
                    EXECUTE_DEPT_NAME = "检验科"

                };
                result.Add(examine);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.19 获取检验结果信息
        /// </summary>
        /// <param name="APPLY_DEPT_CODE">病区代码</param>
        /// <param name="APPLY_IDS">申请单号，多个以逗号分隔</param>
        /// <param name="RESULT_DATE_TIME_FROM">检验结果开始时间</param>
        /// <param name="RESULT_DATE_TIME_TO">检验结果结束时间</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<ExamineResult>> IENMInterface.getExamineResult(string? APPLY_DEPT_CODE, string? APPLY_IDS, DateTime? RESULT_DATE_TIME_FROM, DateTime? RESULT_DATE_TIME_TO, DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<ExamineResult>();

            //连接数据库
            var his = SugarBase.GetIntance();
            var lis = SugarBase.GetIntance("lis");
            //获取系统时间
            var xtsj = his.GetDate();

            //不知道是什么原因，Oracle带日期查询后非常的慢。by songcj 2024-12-03
            //var jysqdlist = await lis.Queryable<L_LIS_SQD, L_JYTMXX, L_PATIENTINFO, L_TESTRESULT, L_TESTDESCRIBE>(
            //    (a, b, c , d, e) => a.DOCTREQUESTNO == b.DOCTREQUESTNO 
            //    && b.SAMPLENO == c.SAMPLENO 
            //    && c.SAMPLENO == d.SAMPLENO 
            //    && d.TESTID == e.TESTID)
            //    .Where((a, b, c, d) => a.JGID == 1 && a.STAYHOSPITALMODE == 2 )
            //    .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DEPT_CODE), (a) => a.SECTION == APPLY_DEPT_CODE)
            //    .WhereIF(!string.IsNullOrWhiteSpace(APPLY_IDS), (a) => APPLY_IDS.Contains(a.DOCTREQUESTNO))
            //    .WhereIF(!string.IsNullOrWhiteSpace(RESULT_DATE_TIME_FROM.ToString()), (a, b, c, d, e) => d.MEASURETIME >= RESULT_DATE_TIME_FROM)
            //    .WhereIF(!string.IsNullOrWhiteSpace(RESULT_DATE_TIME_TO.ToString()), (a, b, c, d, e) => d.MEASURETIME <= RESULT_DATE_TIME_TO)
            //    .Select((a, b, c, d, e) => new {
            //        a.DOCTREQUESTNO,
            //        a.REQUESTTIME,
            //        a.REQUESTER,
            //        a.SQDSTATUS,
            //        a.STAYHOSPITALMODE,
            //        a.BRXZ,
            //        a.PATIENTID,
            //        a.PATIENTNAME,
            //        a.SEX,
            //        a.BIRTHDAY,
            //        a.AGE,
            //        a.AGE_UNIT,
            //        a.SECTION,
            //        a.BED_NO,
            //        a.REQUESTMODE,
            //        a.DIAGNOSTIC,
            //        a.JZXH,
            //        a.BRID,
            //        a.SFZH,
            //        a.LXDH,
            //        a.BAHM,
            //        b.EXAMINAIMCODE,
            //        b.EXAMINAIM,
            //        d.TESTID,
            //        e.CHINESENAME,
            //        d.TESTRESULT,
            //        d.UNIT,
            //        d.HINT,
            //        d.MEASURETIME,
            //        d.REFLO,
            //        d.REFHI,
            //        c.RECEIVER,
            //        c.CHECKOPERATOR,
            //        d.ISWJZ
            //    })
            //    .ToPageListAsync(PAGENUM, PAGESIZE);
            var sql = @"SELECT A.DOCTREQUESTNO AS DOCTREQUESTNO , A.REQUESTTIME AS REQUESTTIME , A.REQUESTER AS REQUESTER ,
	                    A.SQDSTATUS AS SQDSTATUS , A.STAYHOSPITALMODE AS STAYHOSPITALMODE , A.BRXZ AS BRXZ , A.PATIENTID AS PATIENTID ,
	                    A.PATIENTNAME AS PATIENTNAME , A.SEX AS SEX , A.BIRTHDAY AS BIRTHDAY , A.AGE AS AGE , A.AGE_UNIT AS AGE_UNIT , 
	                    A.SECTION AS SECTION , A.BED_NO AS BED_NO , A.REQUESTMODE AS REQUESTMODE , A.DIAGNOSTIC AS DIAGNOSTIC , 
	                    A.JZXH AS JZXH , A.BRID AS BRID , A.SFZH AS SFZH , A.LXDH AS LXDH , A.BAHM AS BAHM , B.EXAMINAIMCODE AS EXAMINAIMCODE ,
	                    B.EXAMINAIM AS EXAMINAIM , D.TESTID AS TESTID , E.CHINESENAME AS CHINESENAME , D.TESTRESULT AS TESTRESULT , 
	                    D.UNIT AS UNIT , D.HINT AS HINT , D.MEASURETIME AS MEASURETIME , D.REFLO AS REFLO , D.REFHI AS REFHI , 
	                    C.RECEIVER AS RECEIVER , C.CHECKOPERATOR AS CHECKOPERATOR , D.ISWJZ AS ISWJZ   
	                    FROM L_LIS_SQD A  ,L_JYTMXX  B ,L_PATIENTINFO  C ,L_TESTRESULT  D ,L_TESTDESCRIBE  E  
	                    WHERE A.DOCTREQUESTNO = B.DOCTREQUESTNO AND B.SAMPLENO = C.SAMPLENO 
	                    AND C.SAMPLENO = D.SAMPLENO AND D.TESTID = E.TESTID ";

            var wheretemp = "AND A.JGID = 1  AND A.STAYHOSPITALMODE = 2 ";

            //填写
            if (!string.IsNullOrWhiteSpace(APPLY_DEPT_CODE))
            {
                wheretemp += $" And A.SECTION = '{APPLY_DEPT_CODE}'";
            }
            if (!string.IsNullOrWhiteSpace(APPLY_IDS))
            {
                wheretemp += $" And A.DOCTREQUESTNO IN '{APPLY_IDS}'";
            }
            if (!string.IsNullOrWhiteSpace(RESULT_DATE_TIME_FROM.ToString()))
            {
                wheretemp += $" And D.MEASURETIME >= to_date('{RESULT_DATE_TIME_FROM}','yyyy-MM-dd HH24:mi:ss')";
            }
            if (!string.IsNullOrWhiteSpace(RESULT_DATE_TIME_TO.ToString()))
            {
                wheretemp += $" And D.MEASURETIME <= to_date('{RESULT_DATE_TIME_TO}','yyyy-MM-dd HH24:mi:ss')";
            }

            sql = sql + wheretemp;

            var jysqdlist = await lis.SqlQueryable<V_IENM_EXAMINERESULT>(sql)
                    .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var jysqd in jysqdlist)
            {
                var examineResult = new ExamineResult
                {
                    PATIENT_ID = jysqd.JZXH?.ToString("0"),
                    INP_NO = jysqd.PATIENTID,
                    VISIT_ID = 1,
                    APPLY_ID = jysqd.DOCTREQUESTNO,
                    APPLY_SERIAL_NUMBER = "1",
                    EXAM_PROJECT_CODE = jysqd.EXAMINAIMCODE,
                    EXAM_PROJECT_NAME = jysqd.EXAMINAIM,
                    APPLY_DEPT_CODE = jysqd.SECTION,
                    APPLY_DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM.ToString() == jysqd.SECTION).First().KSMC,
                    REPORT_ITEM_NAME = jysqd.CHINESENAME,
                    REPORT_ITEM_CODE = jysqd.TESTID,
                    RESULT = jysqd.TESTRESULT,
                    UNITS = jysqd.UNIT,
                    ABNORMAL_INDICATOR = jysqd.HINT,
                    RESULT_DATE_TIME = jysqd.MEASURETIME,
                    REFERENCE_RANGE = $"{jysqd.REFLO}~{jysqd.REFHI}",
                    TRANSCRIPTIONIST = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == jysqd.RECEIVER).First().YGXM,
                    VERIFIED_BY = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == jysqd.CHECKOPERATOR).First().YGXM,
                    ALARM_FLAG = (int)jysqd.ISWJZ

                };
                result.Add(examineResult);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.20 获取检查申请和报告信息
        /// </summary>
        /// <param name="APPLY_DEPT_CODE">开单科室编号</param>
        /// <param name="APPLY_DATE_FROM">检查申请开始时间</param>
        /// <param name="APPLY_DATE_TO">检查申请结束时间</param>
        /// <param name="INP_NO">住院号</param>
        /// <param name="VISIT_ID">住院次数</param>
        /// <param name="APPLY_ID">申请单编号</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<Inspect>> IENMInterface.getInspect(string? APPLY_DEPT_CODE, DateTime? APPLY_DATE_FROM, DateTime? APPLY_DATE_TO, string? INP_NO, int? VISIT_ID, string? APPLY_ID, int PAGENUM, int PAGESIZE)
        {
            var result = new List<Inspect>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var jcsqdlist = await his.Queryable<EMR_JCSQ,ZY_BRRY,EMR_JCXM,YS_ZY_JZJL,EMR_JCBG>( (a,b,c,d,e) => a.JZHM == d.JZHM
            && a.SQDH == c.SQDH && b.ZYH == d.JZXH && a.SQDH == e.SQDH)
                .Where(a => a.JGID == 1 && a.JZLX == 2)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DEPT_CODE), (a) => a.BRKS.ToString() == APPLY_DEPT_CODE)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DATE_FROM.ToString()), (a) => a.KDSJ >= APPLY_DATE_FROM)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_DATE_TO.ToString()), (a) => a.KDSJ <= APPLY_DATE_TO)
                .WhereIF(!string.IsNullOrWhiteSpace(INP_NO), (a,b) => b.ZYHM == INP_NO)
                .WhereIF(!string.IsNullOrWhiteSpace(APPLY_ID), (a, b) => a.SQDH.ToString() == APPLY_ID)
                .Select((a, b, c,d,e) => new
                {
                    a.JZHM,
                    b.ZYHM,
                    c.ZLXMID,
                    c.JCMC,
                    c.SQDH,
                    c.YZXH,
                    a.KDKS,
                    a.KDYS,
                    a.KDSJ,
                    a.JCMD,
                    a.JBMC,
                    c.JCBW,
                    a.JCSJ,
                    a.JCYS,
                    a.BGSJ,
                    a.BGYS,
                    a.ZXKS,
                    e.JCJG,
                    e.LCZD,
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var jcsqd in jcsqdlist)
            {
                var inspect = new Inspect
                {
                    PATIENT_ID = jcsqd.JZHM,
                    INP_NO = jcsqd.ZYHM,
                    VISIT_ID = 1,
                    INPECT_PROJECT_CODE = jcsqd.ZLXMID.ToString("0"),
                    INPECT_PROJECT_NAME = jcsqd.JCMC,
                    APPLY_ID = jcsqd.SQDH.ToString("0"),
                    DOCTOR_ADVICE_ID = jcsqd.YZXH?.ToString("0"),
                    APPLY_DEPT_CODE = jcsqd.KDKS?.ToString("0"),
                    APPLY_DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == jcsqd.KDKS).First().KSMC,
                    APPLY_DOCTOR_CODE = jcsqd.KDYS,
                    APPLY_DOCTOR_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == jcsqd.KDYS).First().YGXM,
                    APPLY_DATE = jcsqd.KDSJ,
                    INPECT_PURPOSE = jcsqd.JCMD,
                    CLINICAL_DIAGNOSIS = jcsqd.JBMC,
                    POSITION = jcsqd.JCBW,
                    EXAM_DATE = jcsqd.JCSJ,
                    INPECT_RESULT = jcsqd.JCJG,
                    DIAGNOSIS_SUGGEST = jcsqd.LCZD,
                    VERIFIED_BY = jcsqd.BGYS,
                    VERIFIED_TIME = jcsqd.BGSJ,
                    EXECUTE_DEPT_CODE = jcsqd.ZXKS?.ToString("0"),
                    EXECUTE_DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == jcsqd.ZXKS).First().KSMC
                };
                result.Add(inspect);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.21 获取临床诊疗项目
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<ClinicalProject>> IENMInterface.getClinicalProject(DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<ClinicalProject>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var zlxmlist = await his.Queryable<EMR_ZLXM>().Where(a => a.ZXBZ == 0).ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var zlxm in zlxmlist)
            {
                var clinicalProject = new ClinicalProject
                {
                    CLINICALPROJECT_CODE = zlxm.ZLXMID.ToString("0"),
                    CLINICALPROJECT_NAME = zlxm.XMMC,
                    DOCTOR_ADVICE_CATEGORY_CODE = zlxm.YDYZLB.ToString("0"),
                    DOCTOR_ADVICE_CATEGORY_NAME = his.Queryable<EMR_YDYZLB>().Where(s => s.YDYZLB == zlxm.YDYZLB).First().LBMC,
                    MNEMONI_CODE = zlxm.PYDM,
                    EXECUTE_DEPT_CODE = zlxm.ZXKS?.ToString("0"),
                    EXECUTE_DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == zlxm.ZXKS).First().KSMC,
                    EXECUTE_TERMINAL = "",
                    UPDATE_TIME = xtsj
                };
                result.Add(clinicalProject);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.22 获取新生儿信息
        /// </summary>
        /// <param name="MOTHER_INP_NO">母亲住院号，多个以逗号分隔</param>
        /// <param name="DEPT_CODE">科室编号</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<Baby>> IENMInterface.getBabies(string? MOTHER_INP_NO, string? DEPT_CODE, DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<Baby>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var xsedjlist = await his.Queryable<BQ_XSEDJ, ZY_BRRY>((a, b) => a.MQZYH == b.ZYH)
                .Where(a => a.JGID == 1)
                .WhereIF(!string.IsNullOrWhiteSpace(MOTHER_INP_NO), (a) => MOTHER_INP_NO.Contains(a.MQZYH.ToString()))
                .WhereIF(!string.IsNullOrWhiteSpace(DEPT_CODE.ToString()), (a,b) => b.BRKS.ToString() == DEPT_CODE)
                .WhereIF(!string.IsNullOrWhiteSpace(UPDATE_TIME.ToString()), (a) => a.YECSNY >= UPDATE_TIME)
                .Select((a, b) => new
                {
                    b.ZYH,
                    b.ZYHM,
                    a.YEWYH,
                    a.YEMZ,
                    a.YEXB,
                    a.YECSNY,
                    b.BRKS
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var xsedj in xsedjlist)
            {
                var baby = new Baby
                {
                    PATIENT_ID = xsedj.ZYH.ToString("0"),
                    INP_NO = xsedj.ZYHM,
                    VISIT_ID = 1,
                    BABY_INP_NO = xsedj.YEWYH.ToString("0"),
                    BABY_NAME = xsedj.YEMZ,
                    GENDER = xsedj.YEXB?.ToString("0"),
                    BIRTHDATA = (DateTime)xsedj.YECSNY,
                    BIRTH_MODE = "",
                    WEIGHT = 0,
                    HEAD_CRCM = "",
                    DEPT_CODE = xsedj.BRKS.ToString("0"),
                    DEPT_NAME = his.Queryable<GY_KSDM>().Where(s => s.JGID == 1 && s.KSDM == xsedj.BRKS).First().KSMC

                };
                result.Add(baby);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.23 获取药品目录
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<DrugDictionary>> IENMInterface.getDrugDictionary(DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<DrugDictionary>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var ypxxlist = await his.Queryable<YK_TYPK>().Where(a => a.ZFPB == 0).ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var ypxx in ypxxlist)
            {
                var drugDictionary = new DrugDictionary
                {
                    DRUG_DIC_CODE = ypxx.YPXH.ToString("0"),
                    PINYIN_CODE = ypxx.PYDM,
                    DRUG_NAME = ypxx.YPMC,
                    SPECIFICATION = ypxx.YPGG,
                    UNITS = ypxx.YPDW,
                    FORMULA_CODE = ypxx.YPSX.ToString("0"),
                    FORMULA_NAME = his.Queryable<YK_YPSX>().Where(s => s.YPSX == ypxx.YPSX).First().SXMC,
                    IS_SKIN_TEST = ypxx.PSPB.ToString("0"),
                    SKIN_TEST_CODE = "",
                    SKIN_TEST_CATE_NAME = "",
                    IS_HIGH_POLICE = ypxx.GWYP?.ToString("0"),
                    HIGH_POLICE_TYPE = "",
                    HIGH_POLICE_INFO = "",
                    UPDATE_TIME = xtsj
                };
                result.Add(drugDictionary);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.24 获取换床信息
        /// </summary>
        /// <param name="DEPT_CODE">科室编号</param>
        /// <param name="CHANGE_TIME_FROM">换床开始时间</param>
        /// <param name="CHANGE_TIME_TO">换床结束时间</param>
        /// <param name="INP_NO">住院号</param>
        /// <param name="VISIT_ID">入院次数</param>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<ChangeBeds>> IENMInterface.getTodayChangeBeds(string? DEPT_CODE, DateTime? CHANGE_TIME_FROM, DateTime? CHANGE_TIME_TO, string? INP_NO, int? VISIT_ID, DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<ChangeBeds>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var hcmxlist = await his.Queryable<ZY_HCMX, ZY_BRRY>((a, b) => a.ZYH == b.ZYH)
                .Where(a => a.JGID == 1)
                .WhereIF(!string.IsNullOrWhiteSpace(DEPT_CODE.ToString()), (a, b) => b.BRKS.ToString() == DEPT_CODE)
                .WhereIF(!string.IsNullOrWhiteSpace(CHANGE_TIME_FROM.ToString()), (a) => a.HCRQ >= CHANGE_TIME_FROM)
                .WhereIF(!string.IsNullOrWhiteSpace(INP_NO), (a,b) => b.ZYHM == INP_NO)
                .Select((a, b) => new
                {
                    b.ZYH,
                    b.ZYHM,
                    b.BRKS,
                    b.BRXM,
                    b.ZZYS,
                    b.ZRHS,
                    a.HQCH,
                    a.HHCH,
                    a.HCRQ
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var hcmx in hcmxlist)
            {
                var changeBeds = new ChangeBeds
                {
                    PATIENT_ID = hcmx.ZYH.ToString("0"),
                    INP_NO = hcmx.ZYHM,
                    VISIT_ID = 1,
                    DEPT_CODE = hcmx.BRKS.ToString("0"),
                    PATIENT_NAME = hcmx.BRXM,
                    ORIGIN_DOCTOR_CODE = hcmx.ZZYS,
                    ORIGIN_DOCTOR_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == hcmx.ZZYS).First().YGXM,
                    PRESENT_DOCTOR_CODE = hcmx.ZZYS,
                    PRESENT_DOCTOR_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == hcmx.ZZYS).First().YGXM,
                    CHANGE_DOCTOR_TIME = null,
                    NURSE_CODE = hcmx.ZRHS,
                    NURSE_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == hcmx.ZRHS).First().YGXM,
                    ORIGIN_BED_NO = hcmx.HQCH,
                    PRESENT_BED_NO = hcmx.HHCH,
                    CHANGE_BED_TIME = hcmx.HCRQ


                };
                result.Add(changeBeds);
            }

            return result;
        }

        /// <summary>
        /// 4.1.1.25 获取患者撤销入科记录
        /// </summary>
        /// <param name="UPDATE_TIME">数据更新时间</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        async Task<List<OutWardRecord>> IENMInterface.getOutWardRecord(DateTime UPDATE_TIME, int PAGENUM, int PAGESIZE)
        {
            var result = new List<OutWardRecord>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            var hcmxlist = await his.Queryable<ZY_BRRY>()
                .Where(a => a.JGID == 1 && a.CYPB == 99)
                .WhereIF(!string.IsNullOrWhiteSpace(UPDATE_TIME.ToString()), (a) => a.CYRQ >= UPDATE_TIME)
                .Select((a) => new
                {
                    a.ZYH,
                    a.ZYHM,
                    a.BRKS,
                    a.BRXM,
                    a.CYRQ
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var hcmx in hcmxlist)
            {
                var outWardRecord = new OutWardRecord
                {
                    INP_NO = hcmx.ZYHM,
                    VISIT_ID = 1,
                    OPERATOR_CODE = "",
                    OPERATOR_NAME = "",
                    OPERATE_TIME = (DateTime)hcmx.CYRQ

                };
                result.Add(outWardRecord);
            }

            return result;
        }

        /// <summary>
        /// 4.1.2.1. 人员调科:把护理人员及该护理人员在 HIS 的权限调到另一个科室，支持同时调到多个科室
        /// </summary>
        /// <param name="NURSE_CODE"></param>
        /// <param name="TRANFROM_DEPT_CODE"></param>
        /// <param name="TRANTO_DEPT_CODE"></param>
        /// <param name="OPERATOR"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        async Task<string> IENMInterface.transferNurse(string NURSE_CODE, string TRANFROM_DEPT_CODE, string TRANTO_DEPT_CODE, string OPERATOR)
        {
            //连接数据库
            var his = SugarBase.GetIntance();

            var ygdm = await his.Queryable<GY_YGDM>().Where(a => a.JGID == 1 && a.ZFPB == 0 && a.YGBH == NURSE_CODE && a.KSDM.ToString() == TRANFROM_DEPT_CODE).FirstAsync();

            if (ygdm == null)
                throw new Exception($"没有查询到员工编号={NURSE_CODE}的员工记录。");

            decimal ksdm = 0.0M;

            if (TRANTO_DEPT_CODE.IndexOf(",") > 0) //存在多个科室取第一个科室代码
            {
                String[] arr = TRANTO_DEPT_CODE.Split(",");
                ksdm = decimal.Parse(arr[0]);
            }
            else
            {
                ksdm = decimal.Parse(TRANTO_DEPT_CODE);
            }

            if (ksdm > 0)
            {
                ygdm.KSDM = ksdm;
            }



            //保存数据
            his.Ado.BeginTran();

            try
            {
                his.Updateable(ygdm)
                .UpdateColumns(s => new { s.KSDM })
                .ExecuteCommand();

                his.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                his.Ado.RollbackTran();

                throw new Exception($"更新数据发生异常：{ex.Message}");
            }

            return "";
        }

        /// <summary>
        /// 4.1.2.2. 离职/退休/注销:护理人员在离职、退休或账号注销时使用
        /// </summary>
        /// <param name="NURSE_CODE"></param>
        /// <param name="TYPE"></param>
        /// <param name="OPERATOR"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        async Task<string> IENMInterface.logOff(string NURSE_CODE, int TYPE, string OPERATOR)
        {
            //连接数据库
            var his = SugarBase.GetIntance();
            var portal = SugarBase.GetIntance("PORTAL");

            var ygdm = await his.Queryable<GY_YGDM>().Where(a => a.JGID == 1 && a.ZFPB == 0 && a.YGBH == NURSE_CODE).FirstAsync();

            if (ygdm == null)
                throw new Exception($"没有查询到员工编号={NURSE_CODE}的员工记录。");

            var xtyh = await portal.Queryable<MH_XTYH>().Where(a => a.JGID == 1 && a.ZXBZ == 0 && a.YHDM == NURSE_CODE).FirstAsync();

            if (xtyh == null)
                throw new Exception($"没有查询到员工编号={NURSE_CODE}的门户系统用户记录。");

            //更新数据
            ygdm.ZFPB = 1;
            xtyh.ZXBZ = 1;

            //保存数据
            his.Ado.BeginTran();
            portal.Ado.BeginTran();

            try
            {
                his.Updateable(ygdm)
                .UpdateColumns(s => new { s.ZFPB })
                .ExecuteCommand();

                portal.Updateable(xtyh)
               .UpdateColumns(s => new { s.ZXBZ })
               .ExecuteCommand();

                his.Ado.CommitTran();
                portal.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                his.Ado.RollbackTran();
                portal.Ado.RollbackTran();

                throw new Exception($"更新数据发生异常：{ex.Message}");
            }

            return "";
        }

        /// <summary>
        /// 4.2.1. 获取患者疾病诊断信息
        /// </summary>
        /// <param name="INP_NO">住院号</param>
        /// <param name="VISIT_ID">入院的次数</param>
        /// <param name="DEPT_CODE">科室编号</param>
        /// <param name="DIAGNOSE_TIME_FROM">诊断开始时间</param>
        /// <param name="DIAGNOSE_TIME_TO">诊断结束时间</param>
        /// <param name="INHOSPITAL">是否在院患者，1：是，0：否</param>
        /// <param name="PAGENUM">页码</param>
        /// <param name="PAGESIZE">每页显示条数</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        async Task<List<Diagnose>> IENMInterface.getDiagnose(string? INP_NO, int? VISIT_ID, string? DEPT_CODE, DateTime? DIAGNOSE_TIME_FROM, DateTime? DIAGNOSE_TIME_TO, int? INHOSPITAL, int PAGENUM, int PAGESIZE)
        {
            var result = new List<Diagnose>();

            //连接数据库
            var his = SugarBase.GetIntance();
            //获取系统时间
            var xtsj = his.GetDate();

            //var cypb = INHOSPITAL switch { 1 => "0", 0 => "1,8", _ => "0,1,8" }; //是否在院患者，1：是，0：否
            var cypb = new decimal?[4];

            if (!string.IsNullOrWhiteSpace(INHOSPITAL.ToString()))
            {
                if (INHOSPITAL == 0) //0：获取全部，1：只获取在院
                {
                    cypb[0] = 0;
                    cypb[1] = 1;
                    cypb[2] = 2;
                    cypb[3] = 8;
                }
                else
                {
                    cypb[0] = 0;
                }
            }

            var jbzdlist = await his.Queryable<ZY_BRRY, YS_ZY_JBZD>((a, b) => a.ZYH.ToString() == b.JZHM)
                .Where((a, b) => a.JGID == 1 && a.CYPB == 99 && b.ZFBZ == 0)
                .WhereIF(!string.IsNullOrWhiteSpace(INP_NO), (a, b) => a.ZYHM == INP_NO)
                .WhereIF(!string.IsNullOrWhiteSpace(DEPT_CODE), (a, b) => a.BRKS.ToString() == DEPT_CODE)
                .WhereIF(!string.IsNullOrWhiteSpace(INHOSPITAL.ToString()), (a) => cypb.Contains(a.CYPB))
                .WhereIF(!string.IsNullOrWhiteSpace(DIAGNOSE_TIME_FROM.ToString()), (a, b) => b.ZDSJ >= DIAGNOSE_TIME_FROM)
                .WhereIF(!string.IsNullOrWhiteSpace(DIAGNOSE_TIME_TO.ToString()), (a, b) => b.ZDSJ <= DIAGNOSE_TIME_TO)
                .Select((a, b) => new
                {
                    a.ZYH,
                    a.ZYHM,
                    a.BRKS,
                    a.BRXM,
                    b.JBXH,
                    b.ZDLB,
                    b.ZXLB,
                    b.JBMC,
                    b.ZDSJ,
                    b.ZDYS,
                    a.RYRQ,
                    a.CYRQ
                })
                .ToPageListAsync(PAGENUM, PAGESIZE);

            foreach (var jbzd in jbzdlist)
            {
                var diagnose = new Diagnose
                {
                    PATIENT_ID = jbzd.ZYH.ToString("0"),
                    INP_NO = jbzd.ZYHM,
                    VISIT_ID = 1,
                    DEPT_CODE = jbzd.BRKS.ToString("0"),
                    DIAGNOSE_CODE = jbzd.JBXH?.ToString("0"),
                    DIAGNOSE_CATEGORY = jbzd.ZDLB,
                    DIAGNOSE_TYPE = jbzd.ZXLB switch { 1 => "中医", 0 => "西医", _ => "西医" },
                    DIAGNOSE = jbzd.JBMC,
                    DIAGNOSE_TIME = jbzd.ZDSJ,
                    DIAGNOSE_DOCTOR_CODE = jbzd.ZDYS,
                    DIAGNOSE_DOCTOR_NAME = his.Queryable<GY_YGDM>().Where(s => s.JGID == 1 && s.YGDM == jbzd.ZDYS).First().YGXM,
                    ADMISSION_TIME = jbzd.RYRQ,
                    LEAVE_TIME = jbzd.CYRQ

                };
                result.Add(diagnose);
            }

            return result;
        }

        /// <summary>
        /// 4.3.1. 按日期查询患者 apache2 评分
        /// </summary>
        /// <param name="date"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <param name="hospitalId"></param>
        /// <param name="appKey"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        Task<ActionResult> IENMInterface.apache2Score(string date, int pageNum, int pageSize, string hospitalId, string appKey)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 4.3.2. 患者 apache2 评分
        /// </summary>
        /// <param name="date"></param>
        /// <param name="pageNum"></param>
        /// <param name="pageSize"></param>
        /// <param name="hospitalId"></param>
        /// <param name="appKey"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        Task<ActionResult> IENMInterface.apacheScore(string date, int pageNum, int pageSize, string hospitalId, string appKey)
        {
            throw new NotImplementedException();
        }
    }
}
